use clap::Parser;
use rust_mcp_sdk::{mcp_server::server_runtime, McpServer, StdioTransport, TransportOptions};
use tracing_subscriber::EnvFilter;

mod cli;
mod config;
mod error;
mod handler;
mod tms_client;
mod tools;

use cli::CommandArguments;
use error::ServiceResult;
use handler::TmsServerHandler;

// Include the generated protobuf code
pub mod proto {
    tonic::include_proto!("tms");
}

#[tokio::main]
async fn main() -> ServiceResult<()> {
    let args = CommandArguments::parse();
    
    // Initialize logging
    let log_level = args.log_level.parse().unwrap_or(tracing::Level::INFO);
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env().add_directive(log_level.into()))
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .init();

    // Start the server
    start_server(args).await
}

pub async fn start_server(args: CommandArguments) -> ServiceResult<()> {
    let transport = StdioTransport::new(TransportOptions::default())?;
    let handler = TmsServerHandler::new(&args).await?;
    let server = server_runtime::create_server(server_details(), transport, handler);
    
    server.start().await?;
    Ok(())
}

pub fn server_details() -> rust_mcp_sdk::schema::InitializeResult {
    rust_mcp_sdk::schema::InitializeResult {
        server_info: rust_mcp_sdk::schema::Implementation {
            name: "tms-mcp".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            title: Some("TMS MCP Server: Transportation Management System tools for AI assistants.".to_string()),
        },
        capabilities: rust_mcp_sdk::schema::ServerCapabilities {
            experimental: None,
            logging: None,
            prompts: None,
            resources: None,
            tools: Some(rust_mcp_sdk::schema::ServerCapabilitiesTools { list_changed: None }),
            completions: None,
        },
        instructions: Some("This server provides comprehensive transportation management tools including vehicle management, order management, transport planning, route optimization, and location tracking.".to_string()),
        meta: None,
        protocol_version: rust_mcp_sdk::schema::LATEST_PROTOCOL_VERSION.to_string(),
    }
}